<template>
    <div class="invoice-receipt-list">
        <el-card shadow="never">
            <template #header>
                <div class="card-header">
                    <span>到票列表</span>
                    <el-button type="primary" @click="goToAdd">添加</el-button>
                </div>
            </template>

            <!-- 条件查询区域 -->
            <el-form :model="queryForm" label-width="100px" size="small" class="query-form" label-position="left">
                <el-row :gutter="16">
                    <el-col :span="8">
                        <el-form-item label="发票">
                            <el-select v-model="queryForm.invoiceId" placeholder="请选择发票" style="width: 100%"
                                :loading="invoiceLoading">
                                <el-option label="全部" :value="0" />
                                <el-option v-for="invoice in invoiceList" :key="invoice.invoiceId"
                                    :label="invoice.invoiceNo" :value="invoice.invoiceId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="支付方式">
                            <el-input v-model="queryForm.keyword" placeholder="用于模糊搜索" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="到票状态">
                            <el-select v-model.number="queryForm.receiptStatus" placeholder="请选择" style="width: 100%">
                                <el-option label="全部" :value="-1" />
                                <el-option label="未收款" value="0" />
                                <el-option label="部分收款" value="1" />
                                <el-option label="已收款" value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="16">
                    <el-col :span="12">
                        <el-form-item label="开始日期">
                            <el-date-picker v-model="queryForm.startDate" type="date" placeholder="选择开始日期"
                                style="width: 200px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束日期">
                            <el-date-picker v-model="queryForm.endDate" type="date" placeholder="选择结束日期"
                                style="width: 200px" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24" style="text-align: right">
                        <el-button type="primary" @click="loadData">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 数据列表 -->
            <el-table :data="tableData" border style="width: 100%" :loading="loading">
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column prop="receiptId" label="到票ID" width="100" />
                <el-table-column prop="invoiceId" label="发票ID" width="100" />
                <el-table-column prop="invoiceNo" label="发票编号" min-width="180" />
                <el-table-column prop="receiptDate" label="收款日期" width="160" :formatter="formatDate" />
                <el-table-column prop="receiptAmount" label="收款金额" width="120" align="right" :formatter="formatMoney" />
                <el-table-column prop="receiptStatusName" label="收款状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.receiptStatus)">{{ row.receiptStatusName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="paymentMethod" label="付款方式" min-width="120" />
                <el-table-column prop="transactionNo" label="交易单号" min-width="180" />
                <el-table-column prop="remarks" label="备注" min-width="180" />
                <el-table-column prop="createName" label="创建人" width="100" />
                <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDateTime" />
                <el-table-column prop="updateName" label="更新人" width="100" />
                <el-table-column prop="updateTime" label="更新时间" width="180" :formatter="formatDateTime" />
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="goToEdit(row.receiptId)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row.receiptId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs } from '@/Http/http'
import { useCounterStore } from '@/stores/counter'

// 定义发票类型接口
interface SalesInvoiceItem {
    invoiceId: number
    invoiceNo: string
    orderId: number
    orderNo: string | null
    customerId: number
    customerName: string
    invoiceAmount: number
    invoiceDate: string
    invoiceType: string
    invoiceStatus: number
    invoiceStatusName: string
    taxRate: number
    taxAmount: number
    subtotalAmount: number
    remarks: string
    createName: string
    createTime: string
    updateTime: string
    updateName: string
    details: any | null
}

// 定义到票列表项类型
interface InvoiceReceiptItem {
    receiptId: number
    invoiceId: number
    invoiceNo: string
    receiptDate: string
    receiptAmount: number
    receiptStatus: number
    receiptStatusName: string
    paymentMethod: string
    transactionNo: string
    remarks: string
    createName: string
    createTime: string
    updateName: string
    updateTime: string
}

// 定义到票查询参数类型
interface InvoiceReceiptQueryParams {
    receiptId: number
    invoiceId: number
    invoiceNo: string
    receiptDate: string
    receiptAmount: number
    receiptStatus: number
    keyword: string
    startDate: string
    endDate: string
}

// 定义分页信息类型
interface Pagination {
    currentPage: number
    pageSize: number
    total: number
}

// 初始化组件
const router = useRouter()
const store = useCounterStore()
const loading = ref(false)
const tableData = ref<InvoiceReceiptItem[]>([])
const invoiceList = ref<SalesInvoiceItem[]>([])
const invoiceLoading = ref(false)

// 初始化查询参数（不含分页参数）
const queryForm = reactive<InvoiceReceiptQueryParams>({
    receiptId: 0,
    invoiceId: 0,
    invoiceNo: '',
    receiptDate: '',
    receiptAmount: 0,
    receiptStatus: -1,
    keyword: '',
    startDate: '',
    endDate: ''
})

// 初始化分页信息
const pagination = reactive<Pagination>({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

/**
 * 获取所有发票列表
 */
const getAllInvoices = () => {
    invoiceLoading.value = true
    APIs.get('/api/SalesInvoice/GetAllSalesInvoiceList').then((res: any) => {
        if (res && res.status === 200 && res.data && res.data.code === 100) {
            invoiceList.value = res.data.data || []
        } else {
            ElMessage.error(res?.data?.msg || '获取发票列表失败')
        }
    }).catch((error: any) => {
        ElMessage.error(error?.response?.data?.message || '请求失败')
    }).finally(() => {
        invoiceLoading.value = false
    })
}

/**
 * 加载到票列表数据
 */
const loadData = () => {
    loading.value = true

    // 构建请求参数，使用pagination中的分页参数
    const params = {
        PageIndex: pagination.currentPage,
        PageSize: pagination.pageSize,
        ReceiptId: queryForm.receiptId > 0 ? queryForm.receiptId : undefined,
        InvoiceId: queryForm.invoiceId > 0 ? queryForm.invoiceId : undefined,
        InvoiceNo: queryForm.invoiceNo || undefined,
        ReceiptStatus: queryForm.receiptStatus !== -1 ? queryForm.receiptStatus : undefined,
        Keyword: queryForm.keyword || undefined,
        StartDate: queryForm.startDate || undefined,
        EndDate: queryForm.endDate || undefined
    }

    // 调用API获取数据
    APIs.get('/api/SalesInvoice/GetInvoiceReceiptList', { params }).then((res: any) => {
        // 处理响应数据
        if (res && res.status === 200 && res.data && res.data.code === 100) {
            const responseData = res.data.data || { data: [], total: 0, totalCount: 0 }
            tableData.value = responseData.data || []
            pagination.total = responseData.totalCount || responseData.total || 0
        } else {
            ElMessage.error(res?.data?.msg || '获取到票列表失败')
        }
    }).catch((error: any) => {
        ElMessage.error(error?.response?.data?.message || '请求失败')
    }).finally(() => {
        loading.value = false
    })
}

/**
 * 重置查询条件
 */
const resetQuery = () => {
    queryForm.receiptId = 0
    queryForm.invoiceId = 0
    queryForm.invoiceNo = ''
    queryForm.receiptDate = ''
    queryForm.receiptAmount = 0
    queryForm.receiptStatus = -1
    queryForm.keyword = ''
    queryForm.startDate = ''
    queryForm.endDate = ''
    // 重置分页参数
    pagination.currentPage = 1
}

/**
 * 跳转到添加页面
 */
const goToAdd = () => {
    router.push('/InvoiceAdd')
}

/**
 * 跳转到编辑页面
 * @param receiptId 到票ID
 */
const goToEdit = (receiptId: number) => {
    router.push(`/InvoiceEdit/${receiptId}`)
}

/**
 * 删除到票记录
 * @param receiptId 到票ID
 */
const handleDelete = (receiptId: number) => {
    ElMessageBox.confirm(
        '确定要删除该到票记录吗？删除后无法恢复。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 构建删除请求参数
        const deleteParams = {
            ReceiptId: receiptId,
            DeleteName: store.Users.userNickname || ''
        }

        // 调用删除API
        APIs.delete('/api/SalesInvoice/DeleteInvoiceReceipt', { params: deleteParams }).then((res: any) => {
            if (res && res.status === 200 && res.data && res.data.code === 100) {
                ElMessage.success('删除成功')
                // 重新加载数据
                loadData()
            } else {
                ElMessage.error('删除失败')
            }
        }).catch((error: any) => {
            ElMessage.error(error?.response?.data?.message || '删除操作失败')
        })
    }).catch(() => {
        // 用户取消删除操作，不需要显示错误提示
    })
}

/**
 * 分页大小变化处理
 * @param size 新的页面大小
 */
const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    loadData()
}

/**
 * 当前页码变化处理
 * @param current 新的页码
 */
const handleCurrentChange = (current: number) => {
    pagination.currentPage = current
    loadData()
}

/**
 * 根据收款状态获取标签类型
 * @param status 收款状态
 * @returns 标签类型
 */
const getStatusTagType = (status: number): string => {
    switch (status) {
        case 0: return 'primary' // 未收款
        case 1: return 'warning' // 部分收款
        case 2: return 'success' // 已收款
        default: return 'info'
    }
}

/**
 * 格式化金额
 * @param row 数据行
 * @param column 列信息
 * @param cellValue 单元格值
 * @returns 格式化后的金额字符串
 */
const formatMoney = (row: any, column: any, cellValue: any) => {
    const n = Number(cellValue || 0)
    return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

/**
 * 格式化日期
 * @param row 数据行
 * @param column 列信息
 * @param cellValue 单元格值
 * @returns 格式化后的日期字符串
 */
const formatDate = (row: any, column: any, cellValue: any) => {
    if (!cellValue) return ''
    const date = new Date(cellValue)
    return date.toLocaleDateString('zh-CN')
}

/**
 * 格式化日期时间
 * @param row 数据行
 * @param column 列信息
 * @param cellValue 单元格值
 * @returns 格式化后的日期时间字符串
 */
const formatDateTime = (row: any, column: any, cellValue: any) => {
    if (!cellValue) return ''
    const date = new Date(cellValue)
    return date.toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
    getAllInvoices()
    loadData()
})
</script>

<style scoped>
.invoice-receipt-list {
    padding: 12px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.query-form {
    margin-bottom: 16px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 6px;
}

/* 确保查询条件对齐的样式 */
.query-form .el-form-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}

/* 确保表单项标签和输入框对齐 */
.query-form .el-form-item__label {
    text-align: right;
    padding-right: 12px;
    width: 100px;
}

/* 确保输入组件的宽度一致 */
.query-form .el-input,
.query-form .el-select,
.query-form .el-date-picker {
    width: 100%;
}

/* 按钮区域样式优化 */
.query-form .el-row:last-child {
    margin-top: 8px;
}

.pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

/* 优化表格行高和单元格内边距 */
:deep(.el-table) {
    font-size: 14px;
}

:deep(.el-table td),
:deep(.el-table th) {
    padding: 10px 12px;
}
</style>